import axios from "axios";
import qs from "qs";

/**
 * 请求JSON数据方法
 * axios二次封装，返回Promise对象，Url在commonUtils中定义
 * @param {*} entranceCode 接口编号
 * @param {*} data 数据
 */
const postTianApi = (url, data = {}) => {
  data['key'] = '235ad1ba89583238f422857b6e3cb2de';
  return new Promise((resolve, reject) => {
    axios({
      url: "http://api.tianapi.com/txapi/" + url,
      method: "post",
      data: qs.stringify(data),
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    })
      .then(response => {
        //如请求状态为200(请求成功，且有状态码result)
        if (response.status === 200 && response.data.code) {
          if (response.data.code === 200) {
            resolve(response.data.newslist);
          } else {
            reject(response.data.msg);
          }
        } else {
          reject("网络错误");
        }
      })
      .catch(() => {
        reject("网络错误");
      });
  });
};

const getTianApi = (url, data = {}) => {
  let getUrl = "http://api.tianapi.com/txapi/"+url+'?key=235ad1ba89583238f422857b6e3cb2de';
  for(let i in data){
    getUrl+=('&'+i+'='+data[i]);
  }
  return new Promise((resolve, reject) => {
    axios.get(getUrl)
      .then(response => {
        //如请求状态为200(请求成功，且有状态码result)
        if (response.status === 200 && response.data.code) {
          if (response.data.code === 200) {
            resolve(response.data.newslist);
          } else {
            reject(response.data.msg);
          }
        } else {
          reject("网络错误");
        }
      })
      .catch(() => {
        reject("网络错误");
      });
  });
};

/**
 * 历史记录相关方法
 */
const searchHistory = {
  getHistory: () => {
    let searchHistory = localStorage.getItem("searchHistory");
    return searchHistory ? JSON.parse(searchHistory) : []; // 返回转成的JSON对象
  },
  addHistory: newValue => {
    let searchHistory = localStorage.getItem("searchHistory");
    let historyArray = searchHistory ? JSON.parse(searchHistory) : [];
    let hasSame = false;
    for (let i = 0; i < historyArray.length; i++) {
      if (historyArray[i].text === newValue.text) {
        historyArray.splice(i, 1);
        historyArray.unshift(newValue);
        hasSame = true;
      }
    }
    if (!hasSame) {
      if (historyArray.length >= 5) {
        historyArray.pop();
      }
      historyArray.unshift(newValue);
    }
    localStorage.setItem("searchHistory", JSON.stringify(historyArray));
  },
  clearnHistory: () => {
    localStorage.setItem("[]");
  }
};
export default {
  postTianApi,
  getTianApi,
  searchHistory
};
